<?php

class Admin_IndexController extends CMS_Controller_Action_Admin {

    public function init() {
        parent::init();
    }

    /**
     * Accion por defecto, muestra el listado de categorias.
     */
    public function indexAction() {
        $category = new CMS_Models_UserCategory();
        $this->view->categories = $category->getAll();
    }

    /**
     * Muestra el listado de usuarios
     */
    public function listusersAction() {
        $request = $this->_request->getParams();
        $category = $request['category'];
        $this->view->category = $category;
        $user = new CMS_Models_User();
        $cat = new CMS_Models_UserCategory();
        $this->view->categoryName = $cat->getName($category);
        $this->view->users = $user->getUsersByCategory($category);
    }

    public function newcategoryAction() {
        $form = $this->addCategoryForm();
        $this->view->form = $form;


        if (!$this->getRequest()->isPost()) {
            return;
        } else {
            if (!$form->isValid($_POST)) {
                $this->view->form = $form;
                return;
            } else {
                $values = $form->getValues();
                $category = new CMS_Models_UserCategory();
                $category = $category->createRow();
                $category->name = $values['common']['name'];
                $category->save();
                $module = new CMS_Models_Module();
                $module->updatePermisions($values['common']['modules'], $category->id);
                $this->_redirect("/admin/index");
            }
        }
    }

    /**
     * Crea un nuevo usuario.
     * Guarda un nuevo usuario en la db
     * si recibe datos por post, sino muestra el formulario ( con o sin errores )
     */
    public function newuserAction() {

        $form = $this->addUserForm();
        $this->view->form = $form;

        if (!$this->getRequest()->isPost()) {
            return;
        } else {
            if (!$form->isValid($_POST)) {
                $this->view->form = $form;
                return;
            } else {
                $values = $form->getValues();
                $user = new CMS_Models_User();
                $user = $user->createRow();
                $user->name = $values['common']['name'];
                $user->last_name =  $values['common']['last_name'];
                $user->email = $values['common']['email'];
                $user->login = $values['common']['login'];
                $user->password = $values['common']['password1'];
                $user->id_category = $values['common']['category'];
                $user->save();
                $this->_redirect("/admin/index/listusers/category/" . $values['common']['category']);
            }
        }
    }

    /**
     * Edicion de un usuario
     */
    public function edituserAction() {
        $form = $this->editUserForm();
        $this->view->form = $form;


        if (!$this->getRequest()->isPost()) {
            return;
        } else {
            if (!$form->isValid($_POST)) {
                $this->view->form = $form;
                return;
            } else {
                $values = $form->getValues();
                $user = new CMS_Models_User();
                $user = $user->getUserById($values['common']['id_user']);
                
                if ($values['common']['password1'] != "")
                    $pass = md5($values['common']['password1']);
                else
                    $pass = $user->password;

                $user->name = $values['common']['name'];
                $user->last_name = $values['common']['last_name'];
                $user->email = $values['common']['email'];
                $user->id_category =  $values['common']['category'];
                $user->login = $values['common']['login'];
                $user->password = $pass;
                $user->save();
                $this->_redirect("/admin/index/listusers/category/" . $values['common']['category']);
            }
        }
    }

    /**
     *
     * Edita una categoria
     * @return unknown_type
     */
    public function editcategoryAction() {
        $form = $this->editCategoryForm();
        $this->view->form = $form;


        if (!$this->getRequest()->isPost()) {
            return;
        } else {
            if (!$form->isValid($_POST)) {
                $this->view->form = $form;
                return;
            } else {
                $values = $form->getValues();
                $module = new CMS_Models_Module();
                $module->updatePermisions($values['common']['modules'], $values['common']['id_category']);
                $category = new CMS_Models_UserCategory();
                $category = $category->getCategoryById($values['common']['id_category']);
                $category->name = $values['common']['name'];
                $category->save();
                $this->_redirect("/admin/index");
            }
        }
    }

    /**
     * Elimina una categoria
     * @return unknown_type
     */
    public function deletecategoryAction() {
        $this->disableView();
        $request = $this->_request->getParams();
        $category = new CMS_Models_UserCategory();
        $category = $category->getCategoryById($request['category']);
        $category->delete();
        $this->_redirect("/admin/index");
    }

    public function deleteuserAction() {
        $this->disableView();
        $request = $this->_request->getParams();
        $id_user = $request['user'];
        $category = $request['category'];
        $user = new CMS_Models_User();
        $user = $user->getUserById($id_user);
        $user->delete();
        $this->_redirect("/admin/index/listusers/category/$category");
    }

    /**
     *
     */
    private function editUserForm() {
        $form = new Zend_Form();
        $form->setAction("/admin/index/edituser")
                ->setMethod('post');
        $form->setAttrib("class", "jNice");
        $id_user = $this->_request->getParam('user');
        $user = new CMS_Models_User();
        $user = $user->getUserById($id_user);
        $common = new Zend_Form_SubForm();
        $name = $common->createElement('text', 'name');
        $name->setAttrib("class", "text-long");
        $name->addValidator('NotEmpty')->setLabel($this->view->t->_('Nombre'))->setRequired(true);
        $name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $name->setValue($user['name']);

        $last_name = $common->createElement('text', 'last_name');
        $last_name->setAttrib("class", "text-long");
        $last_name->addValidator('NotEmpty')->setLabel($this->view->t->_('Apellido'))->setRequired(true);
        $last_name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $last_name->setValue($user['last_name']);

        $email = $common->createElement('text', 'email');
        $email->setAttrib("class", "text-long");
        $email->addValidator('emailAddress')->setLabel($this->view->t->_('E-mail'))->setRequired(true);
        $email->addErrorMessage($this->view->t->_('Direccion_de_mail_no_valida'));
        $email->setValue($user['email']);

        $login = $common->createElement("text", "login");
        $login->setAttrib("class", "text-long");
        $login->addValidator('NotEmpty')->setLabel($this->view->t->_('Nombre_de_usuario'))->setRequired(true);
        $login->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $login->setValue($user['login']);

        $password1 = $common->createElement("password", "password1");
        $password1->setAttrib("class", "text-long");
        $password1->setLabel($this->view->t->_('Contrasenia'));

        $category = $common->createElement("select", "category");
        $categories = new CMS_Models_UserCategory();
        $categories = $categories->getAll();
        $category->setLabel($this->view->t->_('Categoria'));
        $category->addMultiOptions($this->formatCategories($categories));

        $category->setValue($user['id_category']);
        $id = $common->createElement("hidden", "id_user");
        $id->setValue($user['id']);

        $common->addElement($category);
        $common->addElement($name);
        $common->addElement($last_name);
        $common->addElement($email);
        $common->addElement($login);
        $common->addElement($password1);

        $common->addElement($id);
        $form->addSubForms(array("common" => $common));
        $form->addElement('submit', 'add', array('label' => $this->view->t->_('Aceptar')));
        return $form;
    }

    private function formatCategories($categories) {
        $options = array();

        foreach ($categories as $c) {
            $options[$c['id']] = $c['name'];
        }
        return $options;
    }

    /**
     *
     * Formulario para editar una categoría.
     *
     * @return unknown_type
     */
    private function editCategoryForm() {
        $form = new Zend_Form();
        $request = $this->_request->getParams();
        $category = $request['category'];
        $form->setAction("/admin/index/editcategory/category/$category")
                ->setMethod('post');
        //$form->setAttrib("class", "jNice");
        $request = $this->_request->getParams();
        $category = $request['category'];
        $common = new Zend_Form_SubForm();
        $name = $common->createElement('text', 'name');
        $name->setAttrib("class", "text-long");
        $name->addValidator('NotEmpty')->setLabel($this->view->t->_('Nombre'))->setRequired(true);
        $name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $cat = new CMS_Models_UserCategory();
        $name->setValue($cat->getName($category));
        $categories = $common->createElement("select", "modules");
        $categories->setAttrib("multiple", "multiple");
        $categories->setAttrib("class", "multiselect");
        $modules = new CMS_Models_Module();
        $modules = $modules->getAll();
        $categories->setLabel($this->view->t->_('Permisos'));
        $categories->addMultiOptions($this->formatCategories($modules));
        $categories->setIsArray(true);
        $mods = new CMS_Models_Module();
        $categories->setValue($this->formatModules($mods->getModulesByCategory($category)));

        $id = $common->createElement("hidden", 'id_category');
        $id->setValue($category);
        $common->addElement($name);
        $common->addElement($categories);
        $common->addElement($id);
        $form->addSubForms(array("common" => $common));
        $form->addElement('submit', 'add', array('label' => $this->view->t->_('Aceptar')));
        return $form;
    }

    private function formatModules($array) {
        $newArray = array();
        foreach ($array as $a) {
            array_push($newArray, $a['id_module']);
        }
        return $newArray;
    }

    private function addCategoryForm() {
        $form = new Zend_Form();
        $form->setAction("/admin/index/newcategory")
                ->setMethod('post');
        //$form->setAttrib("class", "jNice");
        $common = new Zend_Form_SubForm();
        $name = $common->createElement('text', 'name');
        $name->setAttrib("class", "text-long");
        $name->addValidator('NotEmpty')->setLabel($this->view->t->_('Nombre'))->setRequired(true);
        $name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $common->addElement($name);
        $categories = $common->createElement("select", "modules");
        $categories->setAttrib("multiple", "multiple");
        //$categories->setAttrib("id", "modules");
        //$categories->setAttrib("name", "modules[]");
        $categories->setAttrib("class", "multiselect");
        $modules = new CMS_Models_Module();
        $modules = $modules->getAll();
        $categories->setLabel($this->view->t->_('Permisos'));
        $categories->addMultiOptions($this->formatCategories($modules));
        $categories->setIsArray(true);

        $common->addElement($categories);
        $form->addSubForms(array("common" => $common));
        $form->addElement('submit', 'add', array('label' => $this->view->t->_('Aceptar')));
        return $form;
    }

    /**
     * Metodo que crea el formulario del alta
     * de un usuario.
     */
    private function addUserForm() {
        $form = new Zend_Form();
        $form->setAction("/admin/index/newuser")
                ->setMethod('post');
        $form->setAttrib("class", "jNice");

        $id_user = $this->_request->getParam('user');
        $common = new Zend_Form_SubForm();
        $name = $common->createElement('text', 'name');
        $name->setAttrib("class", "text-long");
        $name->addValidator('NotEmpty')->setLabel($this->view->t->_('Nombre'))->setRequired(true);
        $name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));

        $last_name = $common->createElement('text', 'last_name');
        $last_name->setAttrib("class", "text-long");
        $last_name->addValidator('NotEmpty')->setLabel($this->view->t->_('Apellido'))->setRequired(true);
        $last_name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));

        $email = $common->createElement('text', 'email');
        $email->setAttrib("class", "text-long");
        $email->addValidator('emailAddress')->setLabel($this->view->t->_('E-mail'))->setRequired(true);
        $email->addErrorMessage($this->view->t->_('Direccion_de_mail_no_valida'));

        $login = $common->createElement("text", "login");
        $login->setAttrib("class", "text-long");
        $login->addValidator('NotEmpty')->setLabel($this->view->t->_('Nombre_de_usuario'))->setRequired(true);
        $login->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));

        $password1 = $common->createElement("password", "password1");
        $password1->setAttrib("class", "text-long");
        $password1->setLabel($this->view->t->_('Contrasenia'));
        $password1->addValidator('NotEmpty')->setLabel($this->view->t->_('Contrasenia'))->setRequired(true);
        $password1->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));

        $category = $common->createElement("select", "category");
        $categories = new CMS_Models_UserCategory();
        $categories = $categories->getAll();
        $category->setLabel($this->view->t->_('Categoria'));
        $category->addMultiOptions($this->formatCategories($categories));

        $common->addElement($category);
        $common->addElement($name);
        $common->addElement($last_name);
        $common->addElement($email);
        $common->addElement($login);
        $common->addElement($password1);

        $form->addSubForms(array("common" => $common));
        $form->addElement('submit', 'add', array('label' => $this->view->t->_('Aceptar')));
        return $form;
    }

}

?>